﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace TransposeNotes
{
    public partial class MainForm : Form
    {
        private static Row[] rows;
        private static readonly string[] notes = new[] {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};

        public MainForm()
        {
            InitializeComponent();
            rows = Enumerable.Range(1, notes.Length).Select(i => (Row)this.Controls["row" + i]).ToArray();
        }

        private static IEnumerable<string[]> TransposeScale(int[] keys)
        {
            int counter = 0;
            var transposednotes = new string[keys.Length];
            int keyloc = 0;
            int noteslen = notes.Length;
            while (counter++ < noteslen)
            {
                foreach (int x in keys)
                {
                    transposednotes[keyloc++] = notes[(counter + x - 1)%noteslen];
                }
                keyloc = 0;
                yield return transposednotes;
            }
        }

        //to drag and drop the notes to be played
        private void DragDropKey(object sender, DragEventArgs e)
        {
            //get values from the notes button and put in scale text box
            var x = (Button)e.Data.GetData(typeof (Button));
            ((TextBox)sender).Text = x.Text;
            ((TextBox)sender).Tag = x.Tag.ToString();
        }

        private void DragEnterKey(object sender, DragEventArgs e)
        {
            //only button can be dragged and dropped
            e.Effect = e.Data.GetDataPresent(typeof(Button)) 
                ? DragDropEffects.Copy 
                : DragDropEffects.None;
        }

        private void DragNoteButton(object sender, MouseEventArgs e)
        {
            //send the button since we need text and tag
            ((Button)sender).DoDragDrop(sender, DragDropEffects.Copy | DragDropEffects.Move);
        }

        private void Transpose_Click(object sender, EventArgs e)
        {
            var tags = Enumerable.Range(1, 8).Select(i => notePanel.Controls["note" + i].Tag);
            if (tags.Any(x => x == null))
            {
                MessageBox.Show("You have to fill in all of the scale values.");
                return;
            }
            int count = 0;
            var keys = tags.Select(Convert.ToInt32).ToArray();
            foreach (string[] transposedscale in TransposeScale(keys))
            {
                rows[count++].UpdateRow(transposedscale);
            }
        }
    }
}